這幾天學了物件導向的基礎了,那就來做一個小程式練習吧!我分為兩部分呈現
一.程式外框
二.程式
目標:
1.記錄自己跟朋友的借錢狀況
2.用物件紀錄資訊
最下面兩個Button沒有輸入不能按
架構圖如下:
設計外框:
因為最下面兩個按鈕沒有輸入不能按所以Enabled選擇False,再選擇(Name)取名字上圖紅色的地方
目標:
1.有效將資料保存起來
2.完成按鈕功能
Person Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp4
{
class Person
{
//property
public int Money;
public string Name;
//constructor
public Person(string name,int money)
{
this.Name = name;
this.Money = money;
}
//method
public void Borrow(Person lender,int money)
{
if (lender.Money >= money)
{
lender.Money -= money;
this.Money += money;
}
}
public void Repay(Person lender,int money)
{
if (this.Money >= money)
{
this.Money -= money;
lender.Money += money;
}
}
}
}
程式解說:
分為三個部分
1.property
Name
Money
2.constructor
Person
3.method
Borrow
Repay
主程式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
Person i, friend;
public Form1()
{
InitializeComponent();
}
private void ButtonEnter_Click(object sender, EventArgs e)
{
////////////輸入名字
i = new Person(Text1.Text,0);
friend = new Person(Text2.Text,200000);
ButtonEnter.Enabled = false;
////////////按鈕改變
BorrowButton.Enabled = true;
RepayButton.Enabled = true;
BorrowButton.Text = "跟" + friend.Name + "借1000元";
RepayButton.Text = "還" + friend.Name + "1000元";
///////////標籤改變
MyName.Text = i.Name;
FriendName.Text = friend.Name;
}
private void BorrowButton_Click(object sender, EventArgs e)
{
i.Borrow(friend,1000);
UpdateMoney();
}
private void RepayButton_Click(object sender, EventArgs e)
{
i.Repay(friend, 1000);
UpdateMoney();
}
private void UpdateMoney()
{
MyMoney.Text = "" + i.Money;
FriendMoney.Text = "" + friend.Money;
}
private void Label4_Click(object sender, EventArgs e)
{
}
private void Label5_Click(object sender, EventArgs e)
{
}
private void Label6_Click(object sender, EventArgs e)
{
}
}
}
完成圖:
結語:花了一點時間理解這個程式,不太知道怎麼去解釋各位大大有發現問題請跟我說,小弟我會立馬修正